#include "Driver.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <log/log.h>
#include <iostream>
#include <stdio.h>
#include <cstring>

namespace android
{
    Driver::Driver(string dev) : mDev(dev)
    {
        initDev();
    }

    int Driver::openDev()
    {
        int fd;
        if (mFd > 0)
        {
            return 0;
        }
        fd = open(mDev.c_str(), O_RDWR);
        if (fd == -1)
        {
            ALOGE("%s open failure\n", mDev.c_str());
            return -1;
        }
        mFd = fd;
        return 0;
    }

    int Driver::initDev()
    {
        openDev();
        return 0;
    }

    DriverStrInfo Driver::getStrInfo()
    {
        int cameraID, displayX, displayY, enable;
        int subStrLen;
        char *subStr;
        DriverStrInfo ret;

        ret.mCameraID = -1;
        ret.mDisplayX = -1;
        ret.mDisplayY = -1;
        ret.mEnable = 0;
        ret.mStr = STR_ERROR;

        if (openDev() != 0)
        {
            ALOGE("openDev fail");
            goto out;
        }

        while (1)
        {
            if (mFd < 0) {
                openDev();
            }
            int readLen = read(mFd, (void *)mStrBuf, sizeof(mStrBuf));
            if (readLen < 0)
            {
                ALOGE("read %s fd=%d read_len=%d reopen %s", mDev.c_str(), mFd, readLen, mDev.c_str());
                close(mFd);
                mFd = -1;
                continue;
            }
            ALOGD("%s read : %s", mDev.c_str(), mStrBuf);

            // parse
            int tmp_ret;
            tmp_ret = sscanf(mStrBuf, "cameraID=%d,x=%d,y=%d,enable=%d",
                             &cameraID, &displayX, &displayY, &enable);
            if (EOF == tmp_ret || strlen(mStrBuf) == 0)
            {
                ALOGE("parse fail , len=%d", (int)strlen(mStrBuf));
                continue;
            }

            subStr = strstr(mStrBuf, "str=");
            subStrLen = strlen(subStr);
            memset(mSubBuf, 0, sizeof(mSubBuf));
            memcpy(mSubBuf, subStr + sizeof("str=") - 1, subStrLen - strlen("str="));

            ret.mCameraID = cameraID;
            ret.mDisplayX = displayX;
            ret.mDisplayY = displayY;
            ret.mEnable = enable;
            ret.mStr = mSubBuf;

            break;
        }

    out:
        return ret;
    }
}